﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMSROUTER.StorageManagement;
using SMSROUTER.Business;
using System.Data;
using Utils;
using Settings;
using System.Data.SqlClient;
using StorageManagement;

namespace SMSROUTER.StorageManagement
{
    public class SmsInWaitingStorage : DictionaryStorage<int, SmsInWaiting>
    {
        public static void EnqueuData(SmsInWaiting sms)
        {
            if (sms.RouterID.HasValue)
            {
                EnqueueElementData(sms.RouterID.Value, sms);
            }
        }
        public static void EnqueuData()
        {
            try
            {
                List<int> router_ids = GetKeyNotFullData(SmsRouter.GetInstance().Select(p => p.RouterID));
                if (router_ids.Count > 0)
                {
                    var source = SmsInWaiting.GetForRouter(router_ids);
                    if (source.Count > 0)
                    {
                        foreach (int id in router_ids)
                        {
                            EnqueueElementData(id, source.Where(p => p.RouterID == id));
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static void EnqueueXmlData()
        {
            try
            {
                string fileName = AppSetting.SmsInWaitingBackupFileName;
                if (System.IO.File.Exists(fileName))
                {
                    SqlConnection conn = AppSetting.GetConnection();
                    if (conn.State == ConnectionState.Open)
                    {
                        List<SmsInWaiting> listSms = Xml.ReadFromFileToList<SmsInWaiting>(fileName);
                        // Sau khi đọc file xml xong thì xóa file đi.
                        System.IO.File.Delete(fileName);

                        if (listSms != null && listSms.Count > 0)
                        {
                            foreach (SmsInWaiting item in listSms)
                            {
                                EnqueuData(item);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static void RestoreData()
        {
            try
            {
                var source = DequeueAllElementData();
                SmsInWaiting.BulkInsert(source);
                source.Clear();
            }
            catch (Exception ex)
            {
                Log.InsertLog(ex, null, AppSetting.WarningType.mo_error, null);
            }
        }
    }
}